<template>
  <div :id="id" :style="{height:height,width:width}"/>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: "CreativeRankingChart",
  props: {
    id: {
      type: String,
      default: 'id'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '400px'
    },
    chartData: {
      type: Object | Array
    }
  },
  data() {
    return {
      chart: null
    }
  },
  computed: {
    legendArr() {
      if (this.chartData.yAxis === undefined || this.chartData.yAxis.length === 0) {
        return []
      } else {
        return this.chartData.yAxis.map(item => item.shortId.toString())
      }
    },
    seriesList() {
      if (this.chartData.yAxis === undefined) return []
      return this.chartData.yAxis.map(item => {
        return {
          name: item.shortId.toString(),
          type: 'line',
          data: item.data
        }
      })
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
      window.addEventListener('resize', () => {
        if (this.chart) {
          this.chart.resize()
        }
      })
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
    window.removeEventListener('resize', () => {
      this.chart.resize()
    })
  },
  methods: {
    initChart() {
      // 表格配对象
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: this.legendArr
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          height: '75%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.chartData.xAxis
        },
        yAxis: {
          type: 'value'
        },
        series: this.seriesList
      }
      this.chart = echarts.init(document.getElementById(this.id))
      this.chart.setOption(option)
    }

  }
}
</script>

<style scoped>

</style>
